package com.sgy.netty.business;

import com.alibaba.fastjson.JSON;
import com.sgy.common.ApiResult;
import com.sgy.common.ImRequest;
import com.sgy.common.proto.MsgProtocol;
import com.sgy.dao.MsgrecordMapper;
import com.sgy.netty.handler.ChannelGroups;
import com.sgy.pojo.Msgrecord;
import com.sgy.util.BeanAndMap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.util.HtmlUtils;

import java.net.InetSocketAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MsgProc {

    @Autowired
    private MsgrecordMapper msgrecordMapper;

    //处理聊天室消息
    public ApiResult groupMsg(ChannelHandlerContext ctx, ImRequest request){
        Map resultMap = new HashMap();
        ApiResult result = null;
        Msgrecord msgrecord = new Msgrecord();
        request.getParam().put("content",HtmlUtils.htmlEscape((String) request.getParam().get("content")));
        Msgrecord record = BeanAndMap.mapToBean(request.getParam(), msgrecord);
        record.setCreateTime(new Date());
        InetSocketAddress inetSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = inetSocket.getAddress().getHostAddress();
        record.setIp(clientIP);
        msgrecordMapper.insertSelective(record);
        resultMap.put(MsgProtocol.all_user,msgrecord);
        resultMap.put("param",request.getParam());
        result = ApiResult.success(resultMap);
        result.setUrl(request.getUrl());
        for (Channel channel : ChannelGroups.getAllChannel()) {
            channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(result)));
        }
        return result;
    }
}
